<template>
  <div class="form-user-picker">
    <div>
      <el-button
        :disabled="disabled"
        type="primary"
        icon="el-icon-user"
        round
        size="small"
        @click="handleClick"
        >选择部门</el-button
      >
      <span class="form-user-picker--text">{{ placeholder }}</span>
    </div>
    <NameShow
      style="margin-top: 5px"
      v-if="selected.length"
      :value="selected"
      :props="props"
      isEdit
      :readonly="readonly"
      @change="handleSelect"
    />
    <UserPicker
      ref="userPicker"
      :url="__config__.url"
      :method="__config__.method"
      :searchKey="__config__.searchKey"
      :multiple="multiple"
      :request-props="props.request"
      :response-props="props.response"
      type="dept"
      :selected="selected"
      @ok="handleSelect"
    />
  </div>
</template>

<script>
import UserPicker from "./components/userPicker.vue";
import NameShow from "./components/nameShow.vue";

export default {
  name: "form-org-picker",
  components: {
    UserPicker,
    NameShow,
  },
  model: {
    prop: "value", // 绑定的值，通过父组件传递
    event: "update",
  },
  props: {
    // 绑定的输入值
    value: {
      type: [String],
      default: "",
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    // 可打印
    enablePrint: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: "",
    },

    __config__: {
      type: Object,
      default: () => {},
    },
    props: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      selected: JSON.parse(this.values || "[]"),
    };
  },

  watch: {
    value: {
      immediate: true,
      deep: true,
      handler(newValue, oldValue) {
        this.selected = JSON.parse(newValue || "[]");
      },
    },
  },
  methods: {
    handleClick() {
      if (this.readonly) return;
      this.$refs.userPicker.show();
    },
    handleSelect(values) {
      this.selected = values;
      let newValue = null;
      if (values.length) {
        newValue = JSON.stringify(values);
      }
      this.$emit("update", newValue);
    },
  },
};
</script>

<style lang="scss" scoped>
.form-user-picker {
  .form-user-picker--text {
    margin-left: 10px;
    color: #c0c4cc;
  }
}
</style>
